package com.snail.service.impl;

import com.snail.config.WechatAccountConfig;
import com.snail.dto.OrderDto;
import com.snail.service.PushMessageService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

/**
 * @Author 【swg】.
 * @Date 2017/12/11 16:27
 * @DESC
 * @CONTACT 317758022@qq.com
 */
@Service
@Slf4j
public class PushMessageServiceImpl implements PushMessageService {

    @Autowired
    private WxMpService wxMpService;

    @Autowired
    private WechatAccountConfig wechatAccountConfig;

    @Override
    public void orderStatus(OrderDto orderDto) {
        WxMpTemplateMessage templateMessage = new WxMpTemplateMessage();
        templateMessage.setTemplateId(wechatAccountConfig.getTemplateId().get("orderStatus"));
        templateMessage.setToUser(orderDto.getBuyerOpenid());

        List<WxMpTemplateData> data = Arrays.asList(
                new WxMpTemplateData("first", "亲，请记得收货。","#743A3A"),
                new WxMpTemplateData("keyword1", "微信点餐","#0000FF"),
                new WxMpTemplateData("keyword2", "18868812345","#0000FF"),
                new WxMpTemplateData("keyword3", orderDto.getOrderId(),"#0000FF"),
                new WxMpTemplateData("keyword4", orderDto.getOrderStatusEnum().getMessage(),"#0000FF"),
                new WxMpTemplateData("keyword5", "￥" + orderDto.getOrderAmount(),"#0000FF"),
                new WxMpTemplateData("remark", "欢迎再次光临！","#008000")
        );
        templateMessage.setData(data);
        try {
            wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
        }catch (WxErrorException e) {
            log.error("【微信模版消息】发送失败, {}", e);
            //这里不抛出异常，因为如果抛出，订单完结整个过程会回滚，对于无关紧要的事情，我们尽量不要让他影响主要业务。
        }
    }
}
